<?php
/**
 * Service_Mail
 *
 * Класс User_Notification осуществляет работу по оповещению пользователей о различных событиях
 *
 * @author Егоров Александр <slamer@slamer.ru>
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 1.0
 */
class User_Notification {
  public static $arrNotifications = null;
	public function __construct() {}
	
	/**
	 * Получает список оповещений по электронной почте
	 * 
	 */
	private function getNotifications() {
		Service_Debug::setDebug();
		if (!self::$arrNotifications) {
			$objDB = Service_Database::instance();
			$stmt = "SELECT 
			  `notification`.`action`, `notification`.`subject_ru`, `notification`.`subject_en`, `notification`.`text_ru`, `notification`.`text_en` 
			  FROM `notification`";
			$arrNotifications = $objDB->select($stmt);
			self::$arrNotifications = Service_ArrayConverter::makeKeyArrayFromMultyArray($arrNotifications, 'action');
	  }
		return self::$arrNotifications;
		
	}

  private function _mailHello() {
  	$language = Service_Translate::getLang();
  	$arrNotifications = $this->getNotifications();
  	$hello = $arrNotifications['hello']['text_' . $language];
    $text = '<html>		
<table width="600" cellspacing="0" align="left" style="border-collapse: separate;" >
<!-- header -->
<tr>
	<td width="600" height="8" style="border-top:1px solid #135D9D; border-bottom:1px solid #171819; background:#045398;"></td>
</tr>
<tr>
	<td height="80" width="600" bgcolor="#f0f0f0" style="background:url(cid:bg.png) repeat-x #F0F0F0;border:1px solid #d3d5d7; border-top:0;">
		<table width="600" height="80" cellspacing="0">
			<tr>
				<td width="30"></td>
				<td style="vertical-align:middle;" width="500"><a href="http://hotels.ru"><img border="0" src="cid:logo.png" /></td>
				<td style="vertical-align:middle;" width="20"><a href="http://vk.com"><img border="0" src="cid:vk.png" /></a></td>
				<td style="vertical-align:middle;" width="20"><a href="http://fb.com"><img border="0" src="cid:fb.png" /></a></td>
				<td width="10"></td>
			</tr>
		</table>
	</td>
</tr>
<!-- content -->
<tr>
	<td width="600" style="border-left:1px solid #d3d5d7;border-right:1px solid #d3d5d7;">
		<div style="padding:10px 20px"><h1 style="margin:0px;">' . $hello . '</h1>';
    return $text;
  }

  private function _mailEnd() {
  	$language = Service_Translate::getLang();
  	$arrNotifications = $this->getNotifications();
  	$text = $arrNotifications['end']['text_' . $language];
  	$text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[url]', W_FULLPATH, $text);
    return $text . '</div>
		</td>
	</tr>
	<!-- footer -->
	<tr style="vertical-align:middle;">
		<td height="68" width="600" bgcolor="#f2f6e8" style="border:1px solid #d3d5d7;">
			<table width="600" cellspacing="0">
				<tr valign="bottom">
					<td width="30"></td>
					<td width="190"><b>' . Service_Translate::getText('Бесплатно по России') . '</b></td>
					<td width="190"><b>' . Service_Translate::getText('Санкт-Петербург') . '</b></td>
					<td width="190"><b>' . Service_Translate::getText('Москва') . '</b></td>
				</tr>
				<tr valign="top">
					<td></td>
					<td><font size="4"><b>8 800 555-09-21</b></font></td>
					<td><font size="4"><b>8 812 309-57-60</b></font></td>
					<td><font size="4"><b>8 495 505-63-25</b></font></td>
				</tr>
			</table>
		</td>
	</tr>
</table></html>';
  }
  
  private function _send($strEMail, $subject, $text) {
  	$text = $this->_cssText($text);
    $m = new Service_Amail( 
    	$strEMail, 
			$subject,
			self::_mailHello() . $text . self::_mailEnd(),                    
			"From: " . EMAIL_FROM . "\n"
		);
		$m->file(IMAGES . 'mail/bg.png');
		$m->file(IMAGES . 'mail/vk.png');
		$m->file(IMAGES . 'mail/fb.png');
		$m->file(IMAGES . 'mail/logo.png');
    return $m->send();
  }
  
  private function _cssText($text) {
  	$text = str_replace('<p>', '<p style="color:#000000; font-family: Arial, Helvetica; margin:3px; padding:0px;">', $text);
  	$text = str_replace('<div class="header"><h2>', '<div style="padding:5px 10px;background:#e9f2fb;margin-top:20px;"><h2 style="margin:0px;font-size:20px;">', $text);
  	$text = str_replace('<div class="block"', '<div style="padding:0 10px;"', $text);
  	$text = str_replace('<div class=', '<div style="margin:3px;" class="', $text);
  	return $text;
  }

  /**
   * Метод уведомляет пользователя о его регистрации
   *
   * @param string $strEMail
   * @param string $login
   * @param string $pass
   */
  public function newAccount($strEMail, $login, $pass) {
    $arrNotifications = $this->getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['new_account']['subject_' . $language];
    $text = $arrNotifications['new_account']['text_' . $language];
    $code = Service_Generate::generateApproveCode($strEMail, $login); 
    $confirmationLink = W_FULLPATH . 'auth/approve/' . $code . '/' . $strEMail;
    $text = str_replace('[site]', SITE_NAME, $text);
    $text = str_replace('[email]', $strEMail, $text);
  	$text = str_replace('[login]', $login, $text);
  	$text = str_replace('[pass]', $pass, $text);
  	$text = str_replace('[url]', $confirmationLink, $text);
    
  	return $this->_send($strEMail, $subject, $text);
  }

  /**
   * Метод уведомляет пользователя о создании для него нового аккаунта
   *
   * @param string $strEMail
   * @param string $login
   * @param string $pass
   */
  public function createAccount($strEMail, $login, $pass) {
    $arrNotifications = $this->getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['create_account']['subject_' . $language];
    $text = $arrNotifications['create_account']['text_' . $language];
    
    $code = Service_Generate::generateApproveCode($strEMail, $login); 
    $confirmationLink = W_FULLPATH . 'auth/approve/' . $code . '/' . $strEMail;
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[email]', $strEMail, $text);
  	$text = str_replace('[login]', $login, $text);
  	$text = str_replace('[pass]', $pass, $text);
  	$text = str_replace('[url]', $confirmationLink, $text);
    
  	return $this->_send($strEMail, $subject, $text);
  }

  /**
   * Метод уведомляет пользователя о создании для него нового аккаунта
   *
   * @param string $strEMail
   * @param string $login
   * @param string $pass
   */
  public function createHotelAccount($strEMail, $login, $pass) {
    $arrNotifications = $this->getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['create_hotel_account']['subject_' . $language];
    $text = $arrNotifications['create_hotel_account']['text_' . $language];
    
    $code = Service_Generate::generateApproveCode($strEMail, $login); 
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[email]', $strEMail, $text);
  	$text = str_replace('[login]', $login, $text);
  	$text = str_replace('[pass]', $pass, $text);
    
  	return $this->_send($strEMail, $subject, $text);
  }
  
  /**
   * Оповещает пользователя о создании ему нового пароля
   *
   * @param string $strEMail
   */
  public function recovery($strEMail, $pass) {
    $action = 'recovery';
    $language = Service_Translate::getLang();
  	$arrNotifications = $this->getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];

    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[pass]', $pass, $text);
    
  	return $this->_send($strEMail, $subject, $text);
  }
  
  /**
   * Оповещает пользователя о новом заказе через Booking
   *
   * @param string $strEMail
   */
  public function booking($strEMail, $action, Booking $objBooking, $arrBookingInfo, $arrCountries, Hotel $objHotel, $fullPrice, $hotelCurency, $arrCity, $arrRooms) {
    //$action = 'booking';
    $language = Service_Translate::getLang();
  	$arrNotifications = $this->getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];

    $objServiceBooking = new Service_Booking();
	  $objServiceBooking->arrHotelIds[] = $objBooking->getField('ID_hotel');
	  $objServiceBooking->arrLanguageCodes = array($language);
	  
	  $objViewBlock = new View_Block();
    $info = $objViewBlock->getBookInfo($objBooking, $arrCountries, $objHotel, $fullPrice, $hotelCurency, $arrCity, $arrRooms, $arrBookingInfo);
      
    $text = str_replace('[site]', SITE_NAME, $text);
    $text = str_replace('[url]', '<a class="grey" href="' . W_FULLPATH . Service_Translate::getLangForUrl() . '/cancellation.htm?e_mail=' . $objBooking->getField('e_mail') . '&id=' . $objBooking->getField('id') . '">' . Service_Translate::getText('Отмена бронирования') . '</a>', $text);
  	$text = str_replace('[booking]', $objBooking->getField('id'), $text);
  	$text = str_replace('[pincode]', $objBooking->getField('pincode'), $text);
  	$text = str_replace('[info]', $info, $text);	
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);	
  	return $this->_send($strEMail, $subject, $text);
  }
   
  /**
   * Оповещает администратора о новом фидбэке
   *
   * @param array $arrFeedback - массив с данными
   */
  public function feedback($arrFeedback) {
    $subject = "[" . SITE_NAME . "] Новый feedback";
    $text = '<br />';
    foreach ($arrFeedback as $key => $value) {
    	$text .= str_replace('_', ' ', Service_Function::utf8_first_to_upper($key));
    	$text .= ': ' . $value . '<br />';
    }
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }
  
  /**
   * Оповещает администратора о новом фидбэке
   *
   * @param array $arrFeedback - массив с данными
   */
  public function groupBooking($arrBooking) {
    $subject = "[" . SITE_NAME . "] Групповой заказ";
    $text = '<br />';
    foreach ($arrBooking as $key => $value) {
    	$text .= str_replace('_', ' ', Service_Function::utf8_first_to_upper($key));
    	$text .= ': ' . $value . '<br />';
    }
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }
  
  /**
   * Оповещает администратора о предлоежениях о сотрудничестве
   *
   * @param array $arrFeedback - массив с данными
   */
  public function offertHotel($arrBooking) {
    $subject = "[" . SITE_NAME . "] Предложения сотрудничества";
    $text = '<br />';
    foreach ($arrBooking as $key => $value) {
    	$text .= str_replace('_', ' ', Service_Function::utf8_first_to_upper($key));
    	$text .= ': ' . $value . '<br />';
    }
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }  
  /**
   * Оповещает администратора о заказе с другой формой оплаты
   *
   * @param array $arrBooking - массив с данными
   */
  public function bookingNonCreditCard(array $arrBooking, Hotel $objHotel, $arrBlocks) {
  	Service_Debug::setDebug();
		$objCountry = new Country($arrBooking['country_code']);
		$objCountryDest = new Country($objHotel->getField('country_code'));
		$objCityDest = new City($objHotel->getField('ID_city'));
		$arrBlockIds = array();
		$people = 0;
		foreach ($arrBooking['Room'] as $arrRoom) {
			$blockIds = explode('_', $arrRoom['ID_block']);
			$arrBlockIds[] = $blockIds[0];
			$people += $arrRoom['guest_qty'];
		}
		$subject = "[" . SITE_NAME . "] Заказ без кредитной карты";
    $text = '<br />';
    $text .= '<h2>Информация</h2>';
    $text .= '<p>Фамилия Имя: ' . $arrBooking['booker_last_name'] . ' ' . $arrBooking['booker_first_name'] . '</p>';
    $text .= '<p>E-Mail: ' . $arrBooking['e_mail'] . '</p>';
    $text .= '<p>Тип оплаты: ' . ($arrBooking['payment_type'] == 'Another' ? $arrBooking['other_payment_type'] : $arrBooking['payment_type']) . '</p>';
    $text .= '<h2>Адрес</h2>';
    $text .= '<p>Телефон: ' . $arrBooking['home_phone'] . '</p>';
    $text .= '<p>Страна: ' . $objCountry->getField('country_name_ru') . '</p>';
    $text .= '<p>Город: ' . $arrBooking['city'] . '</p>';

    $text .= '<h2>Гостиница</h2>';
    $text .= '<p>Гостей: ' . $people . '</p>';
    $text .= '<p>Страна: ' . $objCountryDest->tableFields['country_name_ru'] . '</p>';
    $text .= '<p>Город: ' . $objCityDest->tableFields['city_name_ru'] . '</p>';
    $text .= '<p><a href="' . View_Hotel::getUrl($objHotel->tableFields, true) . '?date_arr=' . Service_Date::dateBDToHuman($arrBooking['date_arr']) . '&date_dep=' . Service_Date::dateBDToHuman($arrBooking['date_dep']) . '&adult=' . $arrBooking['adult'] . '">' . View_Hotel::getName($objHotel->tableFields) . '</a></p>';
    $text .= '<p>Дата заезда:'  . Service_Date::dateToRus($arrBooking['date_arr']) . '</p>';
    $text .= '<p>Дата выезда: ' . Service_Date::dateToRus($arrBooking['date_dep']) . '</p>';
    
    $text .= '<h2>Номера</h2>';
    $i = 0;
    foreach ($arrBooking['Room'] as $arrRoom) {
			$blockIds = explode('_', $arrRoom['ID_block']);
    	$text .= '<h3>Номер ' . ++$i . '</h3>';
    	$text .= '<p>Название: ' . $arrBlocks[$arrRoom['ID_block']]['name'];
    	if ($arrRoom['bb']) $text .= ' - завтрак'; 
    	if ($arrRoom['free']) $text .= ' - бесплатная отмена бронирования'; 
    	if ($arrRoom['dr']) $text .= ' - требуется предоплата'; 
    	$text .= '</p>';
	    $text .= '<p>Фамилия Имя: ' . $arrRoom['guest_name'] . '</p>';
	    if ($arrRoom['smoking'] == 1) $text .= '<p>Для некурящих</p>';
	    if ($arrRoom['smoking'] == 2) $text .= '<p>Для курящих</p>';
	    $text .= '<p>Цена: ' . $arrRoom['price'] . ' ' . $arrRoom['currency'] . '</p>';
	    $text .=  '<p>Количество гостей: ' . $arrRoom['guest_qty'] . '</p>';
    }
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }  
  /**
   * Оповещает администратора о заказе с другой формой оплаты
   *
   * @param array $arrBooking - массив с данными
   */
  public function ourBookingNonCreditCard(Booking $arrBooking, Hotel $objHotel) {
		$objCountry = new Country($arrBooking['country_code']);
		$objCountryDest = new Country($objHotel->getField('country_code'));
		$objCityDest = new City($objHotel->getField('ID_city'));
		$arrBlockIds = array();
		$people = 0;
		foreach ($arrBooking['Room'] as $arrRoom) {
			$blockIds = explode('_', $arrRoom['ID_block']);
			$arrBlockIds[] = $blockIds[0];
			$people += $arrRoom['guest_qty'];
		}
		$objRoom = new OurRoom();
  	$arrRooms = $objRoom->getRoomsByIds($arrBlockIds);	
  	$arrRooms = Service_ArrayConverter::makeKeyArrayFromMultyArray($arrRooms, 'ID_our_room');
    $subject = "[" . SITE_NAME . "] Заказ без кредитной карты";
    $text = '<br />';
    $text .= '<h2>Информация</h2>';
    $text .= '<p>Фамилия Имя: ' . $arrBooking['booker_last_name'] . ' ' . $arrBooking['booker_first_name'] . '</p>';
    $text .= '<p>E-Mail: ' . $arrBooking['e_mail'] . '</p>';
    $text .= '<p>Тип оплаты: ' . ($arrBooking['payment_type'] == 'Another' ? $arrBooking['other_payment_type'] : $arrBooking['payment_type']) . '</p>';
    $text .= '<h2>Адрес</h2>';
    $text .= '<p>Телефон: ' . $arrBooking['home_phone'] . '</p>';
    $text .= '<p>Страна: ' . $objCountry->getField('country_name_ru') . '</p>';
    $text .= '<p>Город: ' . $arrBooking['city'] . '</p>';

    $text .= '<h2>Гостиница</h2>';
    $text .= '<p>Гостей: ' . $people . '</p>';
    $text .= '<p>Страна: ' . $objCountryDest->tableFields['country_name_ru'] . '</p>';
    $text .= '<p>Город: ' . $objCityDest->tableFields['city_name_ru'] . '</p>';
    $text .= '<p><a href="' . View_Hotel::getUrl($objHotel->tableFields, true) . '?date_arr=' . Service_Date::dateBDToHuman($arrBooking['date_arr']) . '&date_dep=' . Service_Date::dateBDToHuman($arrBooking['date_dep']) . '&adult=' . $arrBooking['adult'] . '">' . View_Hotel::getName($objHotel->tableFields) . '</a></p>';
    $text .= '<p>Дата заезда:'  . Service_Date::dateToRus($arrBooking['date_arr']) . '</p>';
    $text .= '<p>Дата выезда: ' . Service_Date::dateToRus($arrBooking['date_dep']) . '</p>';
    
    $text .= '<h2>Номера</h2>';
    $i = 0;
    foreach ($arrBooking['Room'] as $arrRoom) {
			$blockIds = explode('_', $arrRoom['ID_block']);
    	$text .= '<h3>Номер ' . ++$i . '</h3>';
    	$text .= '<p>Название: ' . $arrRooms[$blockIds[0]]['room_name_ru'];
    	if ($arrRoom['bb']) $text .= ' - завтрак'; 
    	if ($arrRoom['free']) $text .= ' - бесплатная отмена бронирования'; 
    	if ($arrRoom['dr']) $text .= ' - требуется предоплата'; 
    	$text .= '</p>';
	    $text .= '<p>Фамилия Имя: ' . $arrRoom['guest_name'] . '</p>';
	    if ($arrRoom['smoking'] == 1) $text .= '<p>Для некурящих</p>';
	    if ($arrRoom['smoking'] == 2) $text .= '<p>Для курящих</p>';
	    $text .= '<p>Цена: ' . $arrRoom['price'] . ' ' . $arrRoom['currency'] . '</p>';
	    $text .=  '<p>Количество гостей: ' . $arrRoom['guest_qty'] . '</p>';
    }
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }  

	/**
	 * Оповещает администратора о том что отель хочет опубилковаться
	 * 
	 * @param OurHotel $objOurHotel - объект отеля
	 */  
  public function checkHotel(OurHotel $objOurHotel) {
    $subject = "[" . SITE_NAME . "] Заявка на проверку отеля";
    $text = '<br />';
    $text .= 'Заявка на проверку отеля "' . View_OurHotel::getName($objOurHotel->tableFields) . '"<br />';
    $text .= 'Ссылка <a href="' . W_FULLPATH . 'hms/status/?work_hotel=' . $objOurHotel->id . '">' . W_FULLPATH . 'hms/status/?work_hotel=' . $objOurHotel->id . '</a>';
    
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }    
	/**
	 * Оповещает владельца отеля о том что отель опубликован
	 * 
	 * @param OurHotel $objOurHotel - объект отеля
	 */  
  public function hotelApprove(OurHotel $objOurHotel) {
  	$arrNotifications = $this->getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['hotel_approve']['subject_' . $language];
    $text = $arrNotifications['hotel_approve']['text_' . $language];
    
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[name]', View_OurHotel::getName($objOurHotel->tableFields), $text);
  	$text = str_replace('[link]', '<a href="' . W_FULLPATH . 'hms/">' . W_FULLPATH . 'hms/</a>', $text);
  	$text = str_replace('[site_link]', '<a href="' . View_OurHotel::getUrl($objOurHotel->tableFields, true) . '">' . View_OurHotel::getUrl($objOurHotel->tableFields, true) . '</a>', $text);
  	
  	$eMail = $objOurHotel->getField('contact_person') . ' <' . $objOurHotel->getField('notify_e_mail') . '>';
  	return $this->_send($eMail, $subject, $text);
  }    
	/**
	 * Оповещает владельца отеля о том что отелю отказано в публикации
	 * 
	 * @param OurHotel $objOurHotel - объект отеля
	 */  
  public function hotelReject(OurHotel $objOurHotel) {
  	$arrNotifications = $this->getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['hotel_reject']['subject_' . $language];
    $text = $arrNotifications['hotel_reject']['text_' . $language];
    
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[name]', View_OurHotel::getName($objOurHotel->tableFields), $text);
  	$text = str_replace('[link]', '<a href="' . W_FULLPATH . 'hms/">' . W_FULLPATH . 'hms/</a>', $text);
  	$text = str_replace('[comment]', $objOurHotel->getField('comment'), $text);
    
  	$eMail = $objOurHotel->getField('contact_person') . ' <' . $objOurHotel->getField('notify_e_mail') . '>';
  	return $this->_send($eMail, $subject, $text);
  }    
  

}
?>